package site.helper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

public class FtpClient {
	private String userName; // FTP 登录用户名
	private String password; // FTP 登录密码
	private String ip; // FTP 服务器地址IP地址
	private int port; // FTP 端口
	private FTPClient ftpClient = null; // FTP 客户端代理

	public FtpClient(String userName, String password, String ip, int port) {
		this.userName = userName;
		this.password = password;
		this.ip = ip;
		this.port = port;
	}

	/**
	 *连接
	 * */
	public boolean connectServer() {
		boolean flag = true;
		if (ftpClient == null) {
			int reply;
			try {
				System.out.println("into ftpClient == null");
				ftpClient = new FTPClient();
				ftpClient.setControlEncoding("utf-8"); // 文件名乱码,默认ISO8859-1，不支持中文
				System.out.println("encoding " + ftpClient.getControlEncoding());
				ftpClient.setDefaultPort(port);

				ftpClient.connect(ip);
				ftpClient.login(userName, password);
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				System.out.println("Connected to " + ip);
				System.out.print(ftpClient.getReplyString());
				reply = ftpClient.getReplyCode();
				ftpClient.setDataTimeout(120000);
				if (!FTPReply.isPositiveCompletion(reply)) {
					ftpClient.disconnect();
					System.err.println("FTP server refused connection.");
					flag = false;
				}
			} catch (SocketException e) {
				flag = false;
				e.printStackTrace();
				System.err.println("登录ftp服务器 " + ip + " 失败,连接超时！");
			} catch (IOException e) {
				flag = false;
				e.printStackTrace();
				System.err.println("登录ftp服务器 " + ip + " 失败，FTP服务器无法打开！");
			}
		}
		if (flag == true) {
			System.out.println("登陆ftp服务器成功" + ip);
		}

		System.out.println(flag);
		return flag;
	}

	/**
	 *       * 设置FTP客服端的配置--一般可以不设置       * @return     
	 */

	// private static FTPClientConfig getFtpConfig(){
	// FTPClientConfig ftpConfig=new FTPClientConfig(FTPClientConfig.SYST_UNIX);
	// ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
	// return ftpConfig;
	// }

	/**
	 *通过路径获得远程信息FTPListParseEngine
	 * 拿到服务器的目录下的所有文件listRemoteAllFiles()和disFile()方法
	 * */
	public void listRemoteAllFiles(String path) {
		try {
			FTPListParseEngine f = ftpClient.initiateListParsing(path);
			while (f.hasNext()) {
				FTPFile[] files = f.getNext(5);
				for (FTPFile file : files) {
					disFile(file, path);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disFile(FTPFile file, String path) {
		if (file.isDirectory() && !file.getName().equals(".") && !file.getName().equals("..")) {
			System.out.println(File.separator + file.getName());
			listRemoteAllFiles(path + File.separator + file.getName());
		} else if (!file.getName().equals(".") && !file.getName().equals("..")) {
			System.out.println(file.getName());
		}
	}

	/**
	 *关闭连接
	 * */
	public void closeConnect() {
		System.out.println("关闭ftp服务器");
		try {
			if (ftpClient != null) {
				ftpClient.logout();
				ftpClient.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *下载 remotePath：服务器路径 fileName：服务器端的文件名称 localPath：本地路径
	 * */
	public void downFile(String remotePath, String fileName, String localPath) {
		FTPFile[] fs;
		try {
			ftpClient.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			fs = ftpClient.listFiles();
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					File localFile = new File(localPath + File.separator + ff.getName());

					FileOutputStream is = new FileOutputStream(localFile);
					ftpClient.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 *上传 path：服务器路径 filename：服务器端的文件名称 localFilePath：本地路径 例："D://移动//网址.txt"
	 * */
	public void upFile(String path, String filename, String localFilePath) {
		try {
			File file = new File(localFilePath);
			if (file.length() == 0) {
				throw new Exception("上传文件为空!");
			}

			ftpClient.changeWorkingDirectory(path);
			// success =ftpClient.storeFile(filename, in);
			OutputStream output = ftpClient.storeFileStream(new String(filename.getBytes("GBK"), "iso8859-1"));
			FileInputStream input = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int n = 0;
			System.out.println("开始上传!");
			while (-1 != (n = input.read(buffer))) {
				output.write(buffer, 0, n);
			}
			System.out.println("结束上传!");
			output.close();
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// //////////////////////////////////////////////////////
	public static void main(String[] args) {
		FtpClient ftp = new FtpClient("normal", "normal", "192.168.0.6", 21);
		ftp.connectServer();
		ftp.upFile("/035", "site.rar", "C:/apache-tomcat-6.0.33/webapps/site/tmp/site.rar");
		ftp.closeConnect();
	}

}
